<?php
namespace app\home\controller\sms;

use app\home\controller\Base;

class Handle extends Base
{
	private $params;

	public function __construct(){
		parent::__construct();
		// token验证
		if(false == Base::checkToken()){
			$this->error('token error!');
		}
		// 参数去token
		$params = $this -> request -> post();
		unset($params['token']);
		$this->params = $params;
	}

	/**
	 * 已验证电话用户发送验证码
	 * @return [type] [description]
	 */
	public function send_smscode(){
		if(session('member.is_phone_checked')!=1){
			$this->error('发送失败，请先验证手机号码');
		}
		$member = session('member');
		$phone = $member['phone'];

		$smscode = $this->send($phone);
		// 短信发送接口
		$this -> success('短信发送成功['.$smscode.']');
	}

	/**
	 * 发送验证码
	 * @return [type] [description]
	 */
	public function send_smscode2(){
		$params = $this->params;

		$phone = isset($params['phone'])?$params['phone']:'';
		if(!$phone){
			$this->error('电话号码错误');
		}
		$smscode = $this->send($phone);
		// 短信发送接口
		$this -> success('短信发送成功['.$smscode.']');
	}

	private function send($phone){
		$model = model('sms');
		$smscode = $model::genSmsCode(4);
		$data = [
			'uid' => UID,
			'phone' => $phone,
			'code' => $smscode,
			'ip' => $this->request->ip()
		];
		$model -> save($data);
		return $smscode;
		//file_get_contents('http://v.juhe.cn/sms/send?mobile='.$phone.'&tpl_id=48681&tpl_value='.urlencode('#code#='.$smscode).'&key=f889c3ad996edf8bc471738c0bad44e1');
	}

	/**
	 * 验证已验证用户手机
	 * @return [type] [description]
	 */
	public function check_smscode(){
		$memberInfo = $this->memberInfo;

		if($memberInfo['is_phone_checked']!=1){
			$this->error('错误！手机号码未验证');
		}

		$params = $this->params;
		$validate = $this->validate($params,'PhoneCheck.home_check');
		if(true!==$validate){
			$this->error($validate);
		}

		$smscode = $params['smscode'];
		// 获取当前用户手机号码
		$phone = $memberInfo['phone'];

		$model = model('sms');
		$sms = $model->checkPhoneSmsCode($phone,$smscode,UID);
		if(false==$sms){
			$this->error($model->getError());
		}else{
			// 写入缓存
			\app\common\lib\Cookie::add(HOME_PHONE_CHECK_COOKIE,['ischecked'=>1]);
			// 更改验证码数据库状态
			$model -> where(['id'=>$sms['id']]) -> update(['status'=>1]);
			$this->success('验证成功');
		}

	}

}